package com.atguigu.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizErrorCode;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimall.authserver.cons.OauthConst;
import com.atguigu.gulimall.authserver.cons.SmsConst;
import com.atguigu.gulimall.authserver.feign.memberFeignService;
import com.atguigu.gulimall.authserver.feign.smsFeignService;
import com.atguigu.gulimall.authserver.vo.UserLoginVo;
import com.atguigu.gulimall.authserver.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class indexContrller {

    @Autowired
    smsFeignService smsService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    memberFeignService memberFeignService;

    /**
     * 已登录用户再次点击登录直接进入首页，未登录用户点击登录进入登录页面
     * @param session
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(OauthConst.LOGIN_SESSION_KEY);
        if (attribute!=null){
            return "redirect:http://gulimall.com";
        }else {
            return "login";
        }
    }





    @GetMapping("/sendMessage")
    @ResponseBody
    public R sendMessage(String phone) {
        //ToDO: 接口防刷
        //ToDo: 手机号重复发送
        String res = redisTemplate.opsForValue().get(SmsConst.Sms_Code_Key_Pre_Fix + phone);
        long now = System.currentTimeMillis();

        //验证码
        String code = generateCOde() + "_" + System.currentTimeMillis();

        if (!StringUtils.isEmpty(res)) {
            String time = res.split("_")[1];
            if (now - Long.parseLong(time) < 60000) {
                //不足60s，不能发送
                return R.error(BizErrorCode.SMS_EXCEPTION.getCode(), BizErrorCode.SMS_EXCEPTION.getMessage());
            } else {
                //发送的时间大于了60s，可以再次发送
                smsService.sendMessage(phone, code.split("_")[0]);
                //存入Redis
                redisTemplate.opsForValue().set(SmsConst.Sms_Code_Key_Pre_Fix + phone, code, 10, TimeUnit.MINUTES);
            }

        } else {
            //该手机没有发送过验证码，可以直接发送
            smsService.sendMessage(phone, code.split("_")[0]);
            //存入Redis
            redisTemplate.opsForValue().set(SmsConst.Sms_Code_Key_Pre_Fix + phone, code, 10, TimeUnit.MINUTES);
        }

        return R.ok();
    }

    //生成验证码
    public String generateCOde() {
        ArrayList<String> codeList = new ArrayList<>();
        //验证码
        for (Integer i = 0; i < 10; i++) {
            codeList.add(i.toString());
        }

        Collections.shuffle(codeList);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(codeList.get(i));
        }
        //生成验证码
        return sb.toString();
    }


    @PostMapping("/register")
    public String registerUser(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes) {
        //校验不通过
        if (result.hasErrors()) {
            //按照属性->message的方式返回校验的结果信息
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);

            log.info("error信息:", errors);
            //重定向回去(防止表单的重复提交)
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //校验验证码
        String redisCode = redisTemplate.opsForValue().get(SmsConst.Sms_Code_Key_Pre_Fix + userRegisterVo.getPhone());
        //验证码不为空
        if (!StringUtils.isEmpty(redisCode)) {
            String substring = redisCode.substring(0, 4);
            if (userRegisterVo.getCode().equals(substring)) {
                //删除验证码。
                redisTemplate.delete(SmsConst.Sms_Code_Key_Pre_Fix + userRegisterVo.getPhone());
                //验证码校验通过。调用远程服务。
                R r = memberFeignService.regUser(userRegisterVo);
                if (r.getCode() == 0) {
                    //调用远程服务注册成功，调到登录页面
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("code", (String) r.get("msg"));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
                //验证码校验不通过
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code", "验证码输入不正确");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }


        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code", "验证码已过期");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";

        }


    }

    /**
     * 表单的submit提交，后台不用@requestBody来接受，并不是json数据，而是key——value的样式
     *  登录成功以后向session中存储用户的信息
     * @param userLoginVo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.dealLogin(userLoginVo);
        if (r.getCode() == 0) {
            //登录成功跳回首页
            MemberEntityVo data = r.getData(new TypeReference<MemberEntityVo>() {
            });
            session.setAttribute(OauthConst.LOGIN_SESSION_KEY, data);
            return "redirect:http://gulimall.com/";
        } else {
            //登录失败继续跳回登录页
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
//http://gulimall/oauth2.0/gitee/success?code=1a2585d7369bd2b253aab9f541f71f15644438baad92ac941234e23df1dfe8ae
//    @ResponseBody
//    @GetMapping("/oauth2.0/gitee/success")
//    public String gitee(@RequestParam("code") String code){
//        HashMap<String, Object> paraMap = new HashMap<>();
//        paraMap.put("code",code);
//        System.out.println("回调收集来的code为:"+code);
//        return code;
//    }


}
